<script setup>
import {useRouter} from "vue-router";
import {onBeforeUnmount, onMounted, ref} from "vue";
import axios from "axios";
import flvjs from "flv.js";

const router = useRouter();

const cameraId = ref("");
const videoUrl = ref("");

const flvplayer = ref(null);

const getPlayUrl = (cameraId) => {
  axios.get("/api/getpreviewurls/" + cameraId )
      .then(res => {
        console.log(res.data)
        if(res.data.hasOwnProperty("code") && res.data.code == 0){
          // videoUrl.value = encodeURIComponent(res.data.data.url);
          videoUrl.value = res.data.data.url;
          console.log(res.data.data.url)

          flvplayer.value = flvjs.createPlayer({
            type: "flv",
            isLive: true,
            hasAudio: false,
            url: videoUrl.value
          })
          flvplayer.value.attachMediaElement(document.getElementById("flv-player"));
          flvplayer.value.load();
          flvplayer.value.play();

        }
      })
      .catch(err => {
        console.log(err);
      })
      .finally(() => {

      })
}


onMounted(() => {
  console.log(router.currentRoute.value)
  cameraId.value = router.currentRoute.value.query.cameraId;
  getPlayUrl(cameraId.value);
})

onBeforeUnmount(() => {

  if(flvplayer.value)
  {
    axios.get("/api/endplay/" + cameraId.value);
    flvplayer.value.pause();
    flvplayer.value.unload();
    flvplayer.value.detachMediaElement();
    flvplayer.value.destroy();
    flvplayer.value = null;
  }
})

</script>

<template>

    <video id="flv-player" controls autoplay width="100%">

    </video>

</template>

<style scoped>

</style>